﻿using Newtonsoft.Json.Linq;
using PlanesManager.Models;
using PlanesManager.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;

namespace PlanesManager.Controllers
{
    public class HomeController : Controller
    {
        private PlanesManagerEntities Data = new PlanesManagerEntities();
        public ActionResult Index()
        {
           ViewBag.Message = TempData["Message"];   
           return View();
        }

        [HttpPost]
        public ActionResult Search(string source, string destination, DateTime date)
        {
            if (ModelState.IsValid)
            {
                var flights = Data.Flights.Where(f => f.Routes.Airports.City == source && f.Routes.Airports1.City == destination && f.Departure_Date == date);
                ViewBag.Rooms = Utils.HotelsJsonAPI.getRooms();
                ViewBag.Cars = Utils.RentCarJsonAPI.getCars();
                return View(flights);
            }
            return View();
        }

        public ActionResult Book(string flight, int room, int car)
        {
            if(ModelState.IsValid){

            Bookings book = new Bookings();
            book.Flight_ID = flight;

            string userid = User.Identity.GetUserId();
            AspNetUsers user = Data.AspNetUsers.FirstOrDefault(i => i.Id == userid);
            
            
            var roomIn = HotelsJsonAPI.reservarQuarto(room, 1, "2014-12-12", "2014-12-13",user.Client_Details.FirstName,user.Client_Details.LastName,user.Client_Details.Email,user.Client_Details.Phone);
            var carIn = RentCarJsonAPI.alugarCarro(car, "2014-12-12", "2014-12-13");

            book.InvoiceCar = carIn;
            book.InvoiceHotel = roomIn;

            book.ClientNameOnInvoice =user.Client_Details.FirstName + " " + user.Client_Details.LastName;
            book.ClientDocumentID = "123456789";
            book.CreditCardNumber = "123456789";

            Data.Bookings.Add(book);

            Data.SaveChanges();

            TempData["Message"] = "Reseva efectuada!";
            return RedirectToAction("Home");
            }
            ViewBag.Message = "Erro ao processar a reserva.";
            return View();
        }
    }
}